package com.example.demoapp.bean.util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.airbnb.lottie.animation.content.Content;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.demoapp.bean.User;
import com.example.demoapp.config.URLs;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;
import com.jidcoo.android.widget.commentview.defaults.DefaultCommentModel;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServer {
    public static final String IP = "http://8.130.117.66:8888//comment/getCommentsByUuid";
    public static ExecutorService threadPool = Executors.newSingleThreadExecutor();

    public static void getData(final Handler handler, final int code, Context context,String id,String token) {
        HashMap map = new HashMap();
        map.put("page",0);
        map.put("pageSize", 10);
        map.put("targetId",id);
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.comment_list, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int codes = jsonObject.getInt("code");
                            if (codes == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                Message msg = Message.obtain();
                                msg.what = code;
                                msg.obj = dataArray;
                                handler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            Log.i("getdata出现错误",e.toString());
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", token);
                return headers;
            }
        });
    }
    public static void sendData(final DefaultCommentModel.Comment.Reply reply, final Handler handler, final int code) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = code;
                msg.obj = null;
                handler.sendMessage(msg);
            }
        });
    }

    public static String get(String urlStr) {
        //get的方式提交就是url拼接的方式
        HttpURLConnection connection = null;
        String res = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            //获得结果码
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                //请求成功 获得返回的流
                InputStream is = connection.getInputStream();
                res = inputStream2String(is);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
        return res;
    }


    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];

        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        in.close();
        return out.toString();
    }
}
